from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import logging

def get_toast_text(driver,erro_text):
    """可靠获取B站Toast弹窗文本"""
    # 方案1：通过文本内容直接定位
    try:
        logging.info(f"//*[contains(text(),'{erro_text}')]")
        return WebDriverWait(driver, 3).until(
            EC.visibility_of_element_located((By.XPATH, f"//*[contains(text(),'{erro_text}')]"))
        ).text
    except:
        pass
    
    # 方案2：通过toast结构定位
    try:
        toast = WebDriverWait(driver, 3).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, "div.toast_wp.toast-pos_center"))
        )
        return toast.find_element(By.CLASS_NAME, "toast__content").text
    except:
        pass
    
    # 方案3：检查iframe内容
    try:
        iframes = driver.find_elements(By.TAG_NAME, "iframe")
        for iframe in iframes:
            driver.switch_to.frame(iframe)
            try:
                text = driver.find_element(By.XPATH, f"//*[contains(text(),'{erro_text}')]").text
                if text: return text
            except:
                pass
            finally:
                driver.switch_to.default_content()
    except:
        pass
    
    # 方案4：通过JS直接获取
    return driver.execute_script(f"""
    const toasts = Array.from(document.querySelectorAll('.toast__content'))
        .find(el => el.textContent.includes('{erro_text}'));
    return toasts ? toasts.textContent : null;
    """)



